package com.itheima.tlias.service.impl;

import com.itheima.tlias.annotation.Log;
import com.itheima.tlias.dto.SelectDeptDTO;
import com.itheima.tlias.entity.Dept;
import com.itheima.tlias.mapper.DeptMapper;
import com.itheima.tlias.po.InsertDeptParam;
import com.itheima.tlias.service.DeptService;
import com.itheima.tlias.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    DeptMapper deptMapper;
    @Override
    public List<SelectDeptDTO> selectAll() {
        return deptMapper.selectAll();
    }

    @Override
    public SelectDeptDTO selectById(Integer id) {
        return deptMapper.selectById(id);
    }

    @Log
    @Override
    public ResultUtil updateById(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        Dept selected = deptMapper.selectDeptByName(dept.getName());
        if (Objects.nonNull(selected) && selected.getId() != dept.getId()){
            return ResultUtil.fail("部门名称已存在");
        }
        deptMapper.updateById(dept);
        return ResultUtil.success();
    }

    @Log
    @Override
    public int insertDept(InsertDeptParam param) {
        Dept dept = new Dept();
        dept.setName(param.getName());
        dept.setUpdateTime(LocalDateTime.now());
        dept.setCreateTime(LocalDateTime.now());
        return deptMapper.insertDept(dept);
    }

    @Log
    @Override
    public int deleteById(Integer id) {
        return deptMapper.deleteById(id);
    }

    @Log
    @Override
    public int batchDelete(List<Integer> id) {
        return deptMapper.batchDelete(id);
    }
}
